import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/controller/UserInfoController.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:get/get.dart';

class MineView extends StatefulWidget {
  const MineView({super.key, required this.activeIndex});
  final int? activeIndex;
  @override
  _MineViewState createState() => _MineViewState();
}

class _MineViewState extends State<MineView> {
  // Map<String, dynamic> userInfo = {"id": "", "avatar": "", "nickName": ""};
  // 返回用户头像
  Widget getUserAvatar() {
    if (controller.userInfo["avatar"] != "") {
      return Image.network(
        controller.userInfo["avatar"],
        width: 50,
        height: 50,
        fit: BoxFit.cover,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 50,
      height: 50,
      fit: BoxFit.cover,
    );
  }

  String getUserNickName() {
    if (controller.userInfo["nickName"] != "") {
      return controller.userInfo["nickName"];
    }
    return "用户名";
  }

  // 构建头部信息区域
  Widget _buildHeaderSection() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
      color: const Color(0xFF78B1C5),
      child: Row(
        children: [
          // 头像
          GestureDetector(
            onTap: () {
              PromptAction.showToast('跳转登录页面');
              // 跳转登录页面
              Navigator.pushNamed(context, '/Login');
            },
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(25),
                  child: getUserAvatar(),
                ),
                const SizedBox(width: 15),
                // 用户名
                Text(
                  getUserNickName(),
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          const Spacer(),
          // 完善信息按钮
          GestureDetector(
            onTap: () {
              PromptAction.showToast('跳转信息页面');
              // 跳转信息页面
              Navigator.pushNamed(context, '/Profile');
            },
            child: const Row(
              children: [
                Text(
                  '完善信息',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                ),
                Icon(
                  Icons.chevron_right,
                  color: Colors.white,
                  size: 20,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建功能列表区域
  Widget _buildFunctionList() {
    return Container(
      margin: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          _buildFunctionItem(
            icon: 'assets/images/house_profile_icon@2x.png',
            title: '我的房屋',
            onTap: () {
              // 我的房屋点击事件
            },
          ),
          const Divider(height: 1),
          _buildFunctionItem(
            icon: 'assets/images/repair_profile_icon@2x.png',
            title: '我的报修',
            onTap: () {
              // 我的报修点击事件
            },
          ),
          const Divider(height: 1),
          _buildFunctionItem(
            icon: 'assets/images/visitor_profile_icon@2x.png',
            title: '访客记录',
            onTap: () {
              // 访客记录点击事件
            },
          ),
        ],
      ),
    );
  }

  // 构建单个功能项
  Widget _buildFunctionItem(
      {required String icon,
      required String title,
      required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
        child: Row(
          children: [
            Image.asset(
              icon,
              width: 24,
              height: 24,
            ),
            const SizedBox(width: 15),
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                color: Colors.black87,
              ),
            ),
            const Spacer(),
            const Icon(
              Icons.chevron_right,
              color: Colors.grey,
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  // 构建标题区域
  Widget _buildTitleSection() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      color: const Color(0xFF78B1C5),
      child: const Text(
        '我的',
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    registerEvent();
  }

  registerEvent() {
    emitter.on<LogSuccessEvent>().listen((params) {
      getUserInfo();
    });
  }

  @override
  void didUpdateWidget(covariant MineView oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    // 判断传入的索引 == 1
    if (widget.activeIndex == 1) {
      // 要获取用户信息
      getUserInfo();
    }
  }

  getUserInfo() async {
    final res = await getUserInfoAPI();
    // controller.userInfo = res;
    // setState(() {}); // 让UI具备响应式
    controller.updateUserInfo(res);
  }

  _logout() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text("提示"),
            content: const Text("确定退出登录吗？"),
            actions: [
              TextButton(
                onPressed: () {
                  // 取消退出登录
                  Navigator.pop(context);
                },
                child: const Text("取消"),
              ),
              TextButton(
                onPressed: () {
                  // 确定退出登录
                  tokenManager.removeToken(); // 删除本地token
                  // 用户信息回到初始值
                  // userInfo = {"avatar": "", "nickName": "", "id": ''};
                  // setState(() {});
                  controller
                      .updateUserInfo({"avatar": "", "nickName": "", "id": ''});
                  Navigator.pop(context);
                },
                child: const Text("确定"),
              ),
            ],
          );
        });
  }

  Widget? _buildBottom() {
    if ((controller.userInfo["id"] as String).isEmpty) {
      return null;
    }
    return Container(
      height: 60,
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
              onTap: () {
                // 退出登录
                _logout();
              },
              child: const Text(
                "退出",
                style: TextStyle(color: Colors.red, fontSize: 18),
              )),
        ],
      ),
    );
  }

  UserInfocontroller controller = Get.put(UserInfocontroller());
  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserInfocontroller>(builder: (controller) {
      return AnnotatedRegion<SystemUiOverlayStyle>(
        value: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent, // 透明状态栏，显示下方背景色
          statusBarIconBrightness: Brightness.light, // Android 状态栏图标为浅色
          statusBarBrightness: Brightness.dark, // iOS 状态栏文本浅色
        ),
        child: SafeArea(
          top: false, // 让背景色侵入顶部安全区域
          child: Column(
            children: [
              // 添加一个标题区域，替代AppBar
              Container(
                width: double.infinity,
                padding: EdgeInsets.only(
                  top: MediaQuery.of(context).padding.top +
                      10, // 状态栏高度 + 额外padding
                  bottom: 10,
                ),
                color: const Color(0xFF78B1C5),
                child: const Center(
                  child: Text(
                    "我的",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              _buildHeaderSection(),
              _buildFunctionList(),
              _buildBottom() ?? const Row()
            ],
          ),
        ),
      );
    });
  }
}
